<template>
  <div>
    <el-form-item label="上传" prop="image">
      <el-button icon="el-icon-upload" type="primary" @click="selectFile()">{{text}}</el-button>
      <input  class="hidden" clearable type="file" ref="file"  @input="updateInput($event)" v-on:change="uploadFile ()" v-bind:id="inputId+'-input'"></input>
    </el-form-item>
  </div>
</template>

<script>
  export default {
    name: "bg-file",
    props:{
      text:{
        default:"上传大文件"
      },
      suffixs:{
        default: [],
      },
      inputId:{
        default: "file-upload",
      },
      afterUpload:{
        type:Function,
        default:null,
      }
    },
    data:function (){
      return{

      }
    },
    methods:{
      uploadFile(){
        let _this =this;
        let formData = new window.FormData();
        let file = _this.$refs.file.files[0];

        //生成文件标识
        let key = hex_md5(file.name + file.size + file.type);
        let key10 = parseInt(key,16);
        let key62 = Tool._10to62(key10);
        console.log(key,key10,key62);

        //判断文件格式
        let suffixs = _this.suffixs;
        let fileName = file.name;
        let suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length).toLowerCase();
        let validateSuffix = false;
        for( let i = 0; i < suffixs.length; i++ ){
          if(suffixs[i].toLowerCase() === suffix){
            validateSuffix = true;
            break;
          }
        }
        if (!validateSuffix){
          _this.$message.error('文件格式不正确,只支持'+suffixs.join(","));
          $("#"+_this.inputId+"-input").val("");
          return;
        }


        //文件分片
        let shardSize = 2 * 1024 * 1024; //分片大小
        let shardIndex = 1; //分片索引
        let size = file.size;
        let shardTotal = Math.ceil(size / shardSize ); //总片数

        let param = {
          'shardIndex':shardIndex,
          'shardSize':shardSize,
          'shardTotal':shardTotal,
          'name':file.name,
          'suffix':suffix,
          'size':file.size,
          'key':key62
        };

        _this.check(param);
        this.$message.success( '文件上传成功');
      },

      /*
      * 检查文件分片状态
      * */
      check (param) {
        let _this = this;
        _this.$ajax.get(process.env.VUE_APP_SERVER + '/file/admin/check/' + param.key).then((response)=>{
          let resp = response.data;
          if (resp.success) {
            let obj = resp.content;
            if (!obj) {
              param.shardIndex = 1;
              console.log("没有找到文件记录，从分片1开始上传");
              _this.upload(param);
            } else if (obj.shardIndex === obj.shardTotal) {
              // 已上传分片 = 分片总数，说明已全部上传完，不需要再上传
              this.$message.success('极速秒传成功');
              _this.afterUpload(resp);
              $("#" + _this.inputId + "-input").val("");
            }  else {
              param.shardIndex = obj.shardIndex + 1;
              console.log("找到文件记录，从分片" + param.shardIndex + "开始上传");
              _this.upload(param);
            }
          } else {
            this.$message.error('文件上传失败');
            $("#" + _this.inputId + "-input").val("");
          }
        })
      },

      upload: function (param) {
        let _this = this;
        let shardIndex = param.shardIndex;
        let shardTotal = param.shardTotal;
        let shardSize = param.shardSize;
        let fileShard = _this.getFileShard(shardIndex, shardSize);


        //将图片转为base64进行传输
        let fileReader = new FileReader();
        fileReader.onload = function (e) {
          let base64 = e.target.result;
          param.shard = base64;

          _this.$ajax.post(process.env.VUE_APP_SERVER + '/file/admin/upload', param).then((response) => {
            let resp = response.data;

            console.log("上传文件成功:", resp);
            if (shardIndex < shardTotal) {
              //上传下一个分片
              param.shardIndex = param.shardIndex + 1;
              _this.upload(param);
            } else {
              _this.afterUpload(resp);
              $("#" + _this.inputId + "-input").val("");
            }
          })

        }
        fileReader.readAsDataURL(fileShard);
      },

      getFileShard: function (shardIndex, shardSize) {
        let _this = this;
        let file = _this.$refs.file.files[0];
        let start = (shardIndex - 1) * shardSize; //分片起始位置
        let end = Math.min(file.size, start + shardSize); //结束位置
        let fileShard = file.slice(start, end); //截取数据
        return fileShard;
      },

      selectFile(){
        let _this = this;
        $("#" + _this.inputId + "-input").trigger("click");
      },

      //更新键盘输入input值
      updateInput(e){
        let _this = this;
        _this.$forceUpdate()
      },

    }
  }
</script>